package com.micro.service.auth.server.config.oauth2;

import com.micro.service.auth.server.config.security.MyUserDetailsServiceImpl;
import com.micro.service.auth.server.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author lvxiucai
 * @description
 * @date 2019/10/28
 */
@Component
public class CustomOAuth2FilterConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Autowired
    private MyUserDetailsServiceImpl userDetailsService;

    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        CustomOauth2ProcessingFilter customOauth2ProcessingFilter = new CustomOauth2ProcessingFilter(http.getSharedObject(AuthenticationManager.class));
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();

        AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> preAuthenticatedUserDetailsService = preAuthenticatedAuthenticationToken -> {
            Map<String,?> map = checkTokenEndpoint.checkToken((String) preAuthenticatedAuthenticationToken.getPrincipal());
            if(map != null && map.get("user_name") != null){
                String username = (String) map.get("user_name");
                return new User(Long.parseLong(map.get("userId").toString()),username,null,null,null);
            }
            return null;
        };
        provider.setPreAuthenticatedUserDetailsService(preAuthenticatedUserDetailsService);

        http.authenticationProvider(provider)
        .addFilterBefore(customOauth2ProcessingFilter,UsernamePasswordAuthenticationFilter.class);


    }




}
